﻿namespace SimpleWebServices.Web.Mvc
{
    using System;
    using System.Net;
    using System.Web;
    using System.Web.Mvc;
    using SimpleWebServices.Configuration;
    using SimpleWebServices.Net.Mail;

    [AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
    public sealed class InternalServerErrorAttribute : FilterAttribute, IExceptionFilter
    {
        public void OnException(ExceptionContext filterContext)
        {
            if (null == filterContext)
            {
                throw new ArgumentNullException("filterContext");
            }

            InternalServerErrorSettings settings = InternalServerErrorConfiguration.Settings();
            if (null != settings && settings.Enabled && !filterContext.ExceptionHandled && filterContext.HttpContext.IsCustomErrorEnabled)
            {
                if ((int)HttpStatusCode.InternalServerError == new HttpException(null, filterContext.Exception).GetHttpCode())
                {
                    new InternalServerErrorMailMessage(filterContext).Send();

                    filterContext.Result = (ViewResult)ServiceLocator.Resolve<IViewResult>("InternalServerError");
                    filterContext.ExceptionHandled = true;

                    HttpResponseBase response = filterContext.HttpContext.Response;
                    response.Clear();
                    response.StatusCode = (int)HttpStatusCode.InternalServerError;
                    response.Cache.SetCacheability(HttpCacheability.NoCache);
                    response.TrySkipIisCustomErrors = true;
                }
            }
        }
    }
}